在上一篇中寫了關於陣列的做法
假如今天我們將陣列改成物件,該怎麼去實現它呢?
先給一個全域值:
const person = [
{ name: "John", age: 10 },
{ name: "John", age: 20 },
{ name: "Jay", age: 30 },
{ name: "Jay", age: 40 },
{ name: "Jack", age: 50 },
{ name: "Jack", age: 60 },
];
方法一
使用ES6語法 map + filter + indexOf
let newObject =person.map(item => {
return item.name;
})
console.log(newObject) // ["John", "John", "Jay", "Jay", "Jack", "Jack"]
let value = newObject.filter((item, index) => {
return newObject.indexOf(item) === index;
})
console.log(value) //["John", "Jay", "Jack"]
方法二
跑for迴圈,遍歷陣列法
let newValue = []
let result = []
person.forEach((item) => {
newValue.push(item.name)
})
newValue.forEach((item, key) => {
if(result.indexOf(newValue[key]) === -1) {
result.push(newValue[key])
}
})
console.log(result) //["John", "Jay", "Jack"]
方法三
使用Array from搭配new Set的做法
const value = Array.from(new Set(person.map(item => {
return item.name
})))
console.log(value) //["John", "Jay", "Jack"]
如果還有簡單又好理解的方式,歡迎提出分享唷 謝謝
const persons = [
{ name: "John", age: 10 },
{ name: "John", age: 20 },
{ name: "Jay", age: 30 },
{ name: "Jay", age: 40 },
{ name: "Jack", age: 50 },
{ name: "Jack", age: 60 },
];
const names = Array.from(new Set(persons.map(item => item.name)));
非常感謝良葛格分享做法